<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属仓库" prop="depotId">
        <el-select v-model="queryParams.depotId" placeholder="请选择仓库" clearable size="small"
          @keyup.enter.native="handleQuery">
          <el-option v-for="depot in depotOptions" :key="depot.id" :label="depot.name" :value="depot.id"></el-option>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="库位" prop="depotId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.depotId"-->
      <!--          placeholder="请输入库位"-->
      <!--          clearable-->
      <!--          size="small"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item label="记录名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入品名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['equipment:outStockApply:apply']">出库</el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['equipment:stock:export']"-->
      <!--          >导出</el-button-->
      <!--        >-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inOutRecordList" @selection-change="handleSelectionChange" max-height="550">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="记录名称" align="center" prop="name" />
      <el-table-column label="所属仓库" align="center" prop="depotName" />
      <el-table-column label="操作类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="申请状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改进出库记录对话框 -->
    <el-dialog fullscreen :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rulesOut" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="进出库类型">
              <el-radio-group v-model="form.inOut" :disabled="true">
                <el-radio v-for="dict in inOutOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="类型" :disabled="openDisabled" @change="changeCode($event)">
                <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="编号" prop="code">
              <el-input v-model="form.code" placeholder="请输入编号" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="记录名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入记录名称" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属仓库" prop="depotId">
              <el-select v-model="form.depotId" placeholder="请选择仓库" :disabled="openDisabled">
                <el-option v-for="depot in depotOptions" :key="depot.id" :label="depot.name"
                  :value="depot.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <template v-if="openDisabled">
            <el-col :span="24">
              <el-col :span="12">
                <el-form-item label="申请人" prop="applyName">
                  <el-input v-model="form.applyName" placeholder="请输入编号" :disabled="true" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请时间" prop="applyTime">
                  <el-date-picker :editable="false" clearable size="small" v-model="form.applyTime" type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择记录时间" :disabled="true">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-col>
          </template>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">出库记录-物资列信息</el-divider>
        <el-row :gutter="10" class="mb8" v-if="!openDisabled">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="selectInPro">选择出库物资</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteEqpDepotInOutGoods">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="eqpDepotInOutGoodsList" :row-class-name="rowEqpDepotInOutGoodsIndex"
          @selection-change="handleEqpDepotInOutGoodsSelectionChange" ref="eqpDepotInOutGoods">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column min-width="200" label="编号" prop="code">
            <template slot-scope="scope">
              <el-input v-model="scope.row.code" placeholder="请输入编号" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="物资名称" prop="goodsId">
            <template slot-scope="scope">
              <el-input v-model="scope.row.goodsName" placeholder="请输入物资名称" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="规格" prop="goodsId">
            <template slot-scope="scope">
              <el-input v-model="scope.row.model" placeholder="请输入物资名称" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="出库数量" prop="num">
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.num" placeholder="请输入申请数量" :disabled="openDisabled" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="单位" prop="unit">
            <template slot-scope="scope">
              <el-input v-model="scope.row.unit" placeholder="请输入单位" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="现有库存" prop="inventoryNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.inventoryNum" placeholder="请输入现有库存量" :disabled="true" />
            </template>
          </el-table-column>
          <el-table-column min-width="200" label="可用库存" prop="usableNum">
            <template slot-scope="scope">
              <el-input v-model="scope.row.usableNum" placeholder="请输入可用库存" :disabled="true" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitFormRecord">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <StockOutApplyProducts ref="selectProS" @childFn="parentFn" />
  </div>
</template>

<script>
  import {
    listStock,
    getStock,
    delStock,
    addStock,
    updateStock,
    addOutStockRecord,
    listOutApplyRecord,
  } from "@/api/equipment/materials/stockOutApply";
  import {
    listInOutRecord,
    getInOutRecord,
    delInOutRecord,
    addInOutRecord,
    updateInOutRecord,
  } from "@/api/equipment/materials/stockInOutRecord";
  import { listDepot, getDepot } from "@/api/equipment/materials/depot";
  import StockOutApplyProducts from "./stockOutApplyProducts";
  export default {
    name: "Stock",
    components: {
      StockOutApplyProducts,
    },
    data() {
      return {
        //弹窗是否禁止编辑
        openDisabled: true,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 库存管理表格数据
        inOutRecordList: [],
        statusOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 进出库类型字典
        inOutOptions: [],
        // 操作类型字典
        typeOptions: [],
        // 所属仓库
        depotOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 50,
          code: null,
          name: null,
          inOut: "out",
          type: null,
          applyTime: null,
          checkDirector: null,
          checkDirectorTime: null,
          checkDirectorRemark: null,
          checkPlantLeader: null,
          checkPlantLeaderTime: null,
          checkPlantLeadeRemark: null,
          checkProduction: null,
          checkProductionTime: null,
          checkProductionRemark: null,
          status: null,
        },
        // 进出库记录-物资列表格数据
        eqpDepotInOutGoodsList: [],
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        rulesOut: {
          code: [{ required: true, message: "不能为空", trigger: "blur" }],
          name: [{ required: true, message: "不能为空", trigger: "blur" }],
          depotId: [{ required: true, message: "不能为空", trigger: "blur" }],
          type: [{ required: true, message: "不能为空", trigger: "blur" }],
        },
        // 库查询参数
        depotParams: {
          type: null,
          parentId: null,
          ancestors: null,
        },
      };
    },
    created() {
      this.getList();
      this.getDicts("in_out_stock").then((response) => {
        this.inOutOptions = response.data;
      });
      this.getDicts("out_stock_type").then((response) => {
        this.typeOptions = response.data;
      });
      this.getDicts("out_stock_status").then((response) => {
        this.statusOptions = response.data;
      });
      this.getDepot();
    },
    methods: {
      changeCode(event) {
        this.form.code =
          this.selectDictLabel(this.typeOptions, event) +
          "-" +
          this.parseTime(new Date(), "{y}{m}{d}{h}{i}");
      },
      parentFn(row) {
        for (let i = 0; i < row.length; i++) {
          let goods = {};
          goods.stockId = row[i].id;
          goods.goodsId = row[i].productId;
          goods.goodsSpaceId = row[i].goodsSpaceId;
          goods.code = row[i].productCode;
          goods.goodsName = row[i].productName;
          goods.model = row[i].basicProductInfo.model;
          goods.unit = row[i].unit;
          goods.num = 0;
          goods.stockId = row[i].id;
          goods.inventoryNum = row[i].inventory;
          goods.usableNum = row[i].availableStock;
          this.eqpDepotInOutGoodsList.push(goods);
        }
        let nameeqp = "";
        for (let i = 0; i < this.eqpDepotInOutGoodsList.length; i++) {
          nameeqp = nameeqp + this.eqpDepotInOutGoodsList[i].goodsName + "-";
        }
        nameeqp = nameeqp.substr(0, nameeqp.length - 1);
        this.form.name = nameeqp;
        this.$forceUpdate();
      },
      resetDepot() {
        this.depotParams = {
          type: null,
          parentId: null,
          id: null,
        };
      },
      getDepot() {
        this.loading = true;
        this.resetDepot();
        this.depotParams.type = "01";
        listDepot(this.depotParams).then((response) => {
          this.depotOptions = response.data;
          this.loading = false;
        });
      },
      /** 查询库存管理列表 */
      getList() {
        this.loading = true;
        listOutApplyRecord(this.queryParams).then((response) => {
          this.inOutRecordList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 进出库类型字典翻译
      inOutFormat(row, column) {
        return this.selectDictLabel(this.inOutOptions, row.inOut);
      },
      // 操作类型字典翻译
      typeFormat(row, column) {
        return this.selectDictLabel(this.typeOptions, row.type);
      },
      // 是否关闭
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 出库表单重置
      reset() {
        this.form = {
          id: null,
          code: null,
          name: null,
          depotId: null,
          inOut: "out",
          type: null,
          applyTime: null,
          checkDirector: null,
          checkDirectorTime: null,
          checkDirectorRemark: null,
          checkPlantLeader: null,
          checkPlantLeaderTime: null,
          checkPlantLeadeRemark: null,
          checkProduction: null,
          checkProductionTime: null,
          checkProductionRemark: null,
          status: "01",
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          delFlag: null,
          remark: null,
        };
        this.eqpDepotInOutGoodsList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.openDisabled = false;
        this.open = true;
        this.title = "出库管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.openDisabled = false;
        const id = row.id || this.ids;
        getStock(id).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改库存管理";
        });
      },
      /** 查看按钮 */
      handleView(row) {
        this.reset();
        this.openDisabled = true;
        const id = row.id || this.ids;
        getInOutRecord(id).then((response) => {
          // console.log(response.data);
          this.form = response.data;
          this.eqpDepotInOutGoodsList = response.data.eqpDepotInOutGoodsList;
          this.open = true;
          this.title = "查看出库记录";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.form.id != null) {
              updateStock(this.form).then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              const rLoading = this.openLoading();
              addStock(this.form)
                .then((response) => {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  rLoading.close();
                  this.getList();
                })
                .catch((error) => {
                  rLoading.close();
                });
            }
          }
        });
      },
      /** 提交按钮 */
      submitFormRecord() {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            this.form.eqpDepotInOutGoodsList = this.eqpDepotInOutGoodsList;
            if (this.form.eqpDepotInOutGoodsList == null) {
            } else {
              for (let item of this.form.eqpDepotInOutGoodsList) {
                if (item.num > item.usableNum) {
                  this.$message.closeAll()
                  return this.$message.error(`编号${item.code}的出库数量不可大于可用库存`);
                }
              }
              const rLoading = this.openLoading();
              addOutStockRecord(this.form)
                .then((response) => {
                  this.msgSuccess("出库成功");
                  this.open = false;
                  rLoading.close();
                  this.getList();
                })
                .catch((error) => {
                  rLoading.close();
                });
            }
          }
        });
      },
      // // 多选框选中数据
      // handleSelectionChange(selection) {
      //   this.ids = selection.map((item) => item.id);
      //   this.single = selection.length !== 1;
      //   this.multiple = !selection.length;
      // },
      /** 进出库记录-物资列序号 */
      rowEqpDepotInOutGoodsIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      selectInPro() {
        if (this.form.depotId != null) {
          this.$refs.selectProS.show(this.form.depotId);
        } else {
          this.$message({
            message: "请先选择所属库位！",
            type: "warning",
          });
        }
      },
      /** 进出库记录-物资列删除按钮操作 */
      handleDeleteEqpDepotInOutGoods() {
        if (this.checkedEqpDepotInOutGoods.length == 0) {
          this.$alert("请先选择要删除的进出库记录-物资列数据", "提示", {
            confirmButtonText: "确定",
          });
        } else {
          this.eqpDepotInOutGoodsList.splice(
            this.checkedEqpDepotInOutGoods[0].index - 1,
            1
          );
          let nameeqp = "";
          for (let i = 0; i < this.eqpDepotInOutGoodsList.length; i++) {
            nameeqp = nameeqp + this.eqpDepotInOutGoodsList[i].goodsName + "-";
          }
          nameeqp = nameeqp.substr(0, nameeqp.length - 1);
          this.form.name = nameeqp;
        }
      },
      /** 单选框选中数据 */
      handleEqpDepotInOutGoodsSelectionChange(selection) {
        if (selection.length > 1) {
          this.$refs.eqpDepotInOutGoods.clearSelection();
          this.$refs.eqpDepotInOutGoods.toggleRowSelection(selection.pop());
        } else {
          this.checkedEqpDepotInOutGoods = selection;
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm(
          '是否确认删除库存管理编号为"' + ids + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delStock(ids);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(() => { });
      },
      /** 导出按钮操作 */
      // handleExport() {
      //   this.download(
      //     "equipment/stock/export",
      //     {
      //       ...this.queryParams,
      //     },
      //     "库存管理" + this.parseTime(new Date()) + ".xlsx"
      //   );
      // },
    },
  };
</script>